﻿///////////////////////////////////////////////////////////////////////////////
//
//  This source is part of the  "Managed Task Framework.NET Runtime"  (MTF.NET Runtime).
//
//
//  Copyright (c) 2011, Multicore Consulting Limited (UK)
//  All rights reserved.
//  http://www.multicoreconsulting.co.uk
//
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions
//  are met:
//
//  -  Redistributions of source code must retain the above copyright
//     notice, this list of conditions and the following disclaimer.
//  -  Redistributions in binary form must reproduce the above copyright
//     notice, this list of conditions and the following disclaimer in
//     the documentation and/or other materials provided with the
//     distribution.
//  -  Neither the name of Multicore Consulting Limited nor the names of
//     its contributors may be used to endorse or promote products
//     derived from this software without specific prior written
//     permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
//  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
//  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
//  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
//  COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
//  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
//  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
//  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
//  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
//  POSSIBILITY OF SUCH DAMAGE.
//
///////////////////////////////////////////////////////////////////////////////

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace MTFOrg.MTF.MTFRuntime
{
    /// <summary>
    /// Task manager class.
    /// </summary>
    public abstract class TaskManager : ITaskManager
    {
        /// <summary>
        /// Prototype validator.
        /// </summary>
        protected PrototypeValidator m_PrototypeValidator;

        /// <summary>
        /// Connection manager.
        /// </summary>
        protected ConnectionManager m_ConnectionManager;

        /// <summary>
        /// Registered task managers.
        /// </summary>
        protected static List<ITaskManager> m_TaskManagers;

        /// <summary>
        /// Flag indicating whether task managers have been disposed.
        /// </summary>
        protected static bool m_IsDisposed = false;

        /// <summary>
        /// Constructor
        /// </summary>
        public TaskManager()
        {
            m_PrototypeValidator = GetPrototypeValidator();
            m_ConnectionManager = GetConnectionManager();

            if (m_TaskManagers == null)
                m_TaskManagers = new List<ITaskManager>();

            m_TaskManagers.Add(this);
        }

        /// <summary>
        /// Asynchronous message send.
        /// </summary>
        /// <param name="newMessage">Message to send</param>
        /// <param name="connection">Connection to send message on</param>
        public abstract void QueueMessage(IMessage newMessage, IConnection connection);
        
		/// <summary>
		/// Asynchronous event send
		/// </summary>
		/// <param name="newMessage">Message to send</param>
		/// <param name="connection">Connection to send event on</param>
        /// <param name="threadIndex">Index of preferred thread for execution</param>
        public abstract void QueueMessage(IMessage newMessage, IConnection connection, int threadIndex);

        /// <summary>
        /// Synchronous message send.
        /// </summary>
        /// <param name="newMessage">Message to send</param>
        /// <param name="connection">Connection to send message on</param>
        public abstract void SendMessage(IMessage newMessage, IConnection connection);

        /// <summary>
        /// Adds new work to the queue for the worker thread with the lightest load.
        /// </summary>
        /// <param name="waitCallback">Call-back executed by the worker thread</param>
        /// <param name="state">State to pass to the call-back function</param>
        /// <param name="priority">Execution priority of the work item</param>
        public abstract void QueueUserWorkItem(WaitCallback waitCallback, object state, int priority);

        /// <summary>
        /// Adds new work to the queue for a specific worker thread.
        /// </summary>
        /// <param name="waitCallback">Call-back executed by the worker thread</param>
        /// <param name="state">State to pass to the call-back function</param>
        /// <param name="priority">Execution priority of the work item</param>
        /// <param name="threadIndex">Index of thread to run task on</param>
        /// <param name="isGui">Whether to run work items in the GUI worker pool</param>
        public abstract void QueueUserWorkItem(WaitCallback waitCallback, object state, int priority, int threadIndex, bool isGui);

        /// <summary>
        /// Filters out connections that are not allowed.
        /// </summary>
        /// <param name="newConnections">List of requested connections</param>
        /// <returns>List of allowed connections</returns>
        public ConnectionList FilterConnections(ConnectionList newConnections)
        {
            return m_ConnectionManager.FilterConnections(newConnections);
        }

        /// <summary>
        /// Default prototype validation function always allows connection.
        /// </summary>
        /// <param name="connectionPoints">Points to validate connection for</param>
        /// <returns>true if points can be connected, otherwise false</returns>
        public bool CanConnectPoints(IConnectionPoint sourceConnectionPoint, IConnectionPoint targetConnectionPoint)
        {
            return m_PrototypeValidator.CanConnectPoints(sourceConnectionPoint, targetConnectionPoint);
        }

        /// <summary>
        /// Gets a new instance of a prototype validator.
        /// </summary>
        /// <returns>Prototype validator</returns>
        public virtual PrototypeValidator GetPrototypeValidator()
        {
            return new PrototypeValidator();
        }

        /// <summary>
        /// Gets a new instance of a connection manager.
        /// </summary>
        /// <returns>Connection manager</returns>
        public virtual ConnectionManager GetConnectionManager()
        {
            return new ConnectionManager();
        }

        /// <summary>
        /// Disposes of the task manager and its resources.
        /// <param name="force">forces workers to abort immediately</param>
        /// </summary>
        public virtual void Dispose(bool force = false)
        {
            m_TaskManagers.Remove(this);
        }

        /// <summary>
        /// Static function for disposing of all task managers.
        /// <param name="force">forces workers to abort immediately</param>
        /// </summary>
        public static void DisposeAll(bool force = false)
        {
            // Prevent subsequent dispose requests
            if (m_IsDisposed)
                return;

            m_IsDisposed = true;

            if (m_TaskManagers == null) return;

            foreach (ITaskManager taskManager in m_TaskManagers)
                taskManager.Dispose(force);

            m_TaskManagers.Clear();

            m_IsDisposed = false;
        }

        /// <summary>
        /// Gets whether the task managers have been disposed.
        /// </summary>
        /// <returns>true if disposed, otherwise false</returns>
        public static bool IsDisposed()
        {
            return m_IsDisposed;
        }

        /// <summary>
        /// Determines if shutdown of the worker threads has completed.
        /// </summary>
        /// <returns>true if shutdown complete, otherwise false</returns>
        public abstract bool IsShutdown();

        /// <summary>
        /// Finds the specified interface and returns it.
        /// </summary>
        /// <param name="path">Path of interface to return</param>
        /// <returns>Interface with specified path</returns>
        /// <exception cref="System.ArgumentNullException" />
        /// <exception cref="System.OutOfMemoryException" />
        public object FindInterface(string path)
        {
            return InterfaceManager.Find(path);
        }

        /// <summary>
        /// Registers the specified interface.
        /// </summary>
        /// <param name="path">Path of interface</param>
        /// <param name="ifceObject">Interface object to register</param>
        /// <exception cref="System.ArgumentNullException" />
        /// <exception cref="System.OutOfMemoryException" />
        /// <exception cref="MTFOrg.MTF.MTFRuntime.InterfaceAlreadyRegisteredException" />
        public void RegisterInterface(string path, object ifceObject)
        {
            InterfaceManager.Register(path, ifceObject);
        }

        /// <summary>
        /// Current thread-specific thread index.
        /// </summary>
        [ThreadStatic] private static int m_CurrentThreadIndex;

        /// <summary>
        /// Gets or sets the current thread index.
        /// </summary>
        public static int CurrentThreadIndex
        {
            get
            {
                return m_CurrentThreadIndex;
            }

            set
            {
                m_CurrentThreadIndex = value;
            }
        }
    }
}
